using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using WeWorkApp.Api.Models.Common;
using WeWorkApp.Api.Models.WeChat;
using WeWorkApp.Api.Services;

namespace WeWorkApp.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class CustomerController(IWeChatWorkService weChatWorkService, ILogger<CustomerController> logger)
        : ControllerBase
    {
        #region 获取客户详情

        /// <summary>
        /// 获取客户详情
        /// </summary>
        /// <param name="externalUserId">外部联系人的userid</param>
        /// <param name="corpId">企业ID（可选，如果不传则使用默认配置）</param>
        /// <returns>客户详情信息</returns>
        [HttpGet("{externalUserId}")]
        public async Task<ActionResult<ApiResponse<CustomerDetailDto>>> GetCustomerDetail(
            [FromRoute] string externalUserId,
            [FromQuery] string? corpId = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(externalUserId))
                {
                    return BadRequest(ApiResponse<CustomerDetailDto>.Error("外部联系人ID不能为空"));
                }

                logger.LogInformation("开始获取客户详情: ExternalUserId={ExternalUserId}, CorpId={CorpId}",
                    externalUserId, corpId);

                var customerDetail = await weChatWorkService.GetCustomerDetailAsync(externalUserId, corpId);

                logger.LogInformation("成功获取客户详情: ExternalUserId={ExternalUserId}, Name={Name}",
                    externalUserId, customerDetail.Name);

                return Ok(ApiResponse<CustomerDetailDto>.Success(customerDetail, "获取客户详情成功"));
            }
            catch (UnauthorizedAccessException ex)
            {
                logger.LogWarning(ex, "获取客户详情时权限不足: ExternalUserId={ExternalUserId}", externalUserId);
                return Unauthorized(ApiResponse<CustomerDetailDto>.Error(401, "权限不足，请检查应用授权"));
            }
            catch (ArgumentException ex)
            {
                logger.LogWarning(ex, "获取客户详情时参数错误: ExternalUserId={ExternalUserId}", externalUserId);
                return BadRequest(ApiResponse<CustomerDetailDto>.Error(400, ex.Message));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取客户详情时发生异常: ExternalUserId={ExternalUserId}", externalUserId);
                return StatusCode(500, ApiResponse<CustomerDetailDto>.Error(500, "服务器内部错误，请稍后重试"));
            }
        }

        #endregion

        #region 批量获取客户详情

        /// <summary>
        /// 批量获取客户详情
        /// </summary>
        /// <param name="request">批量获取请求</param>
        /// <returns>客户详情列表</returns>
        [HttpPost("batch")]
        public async Task<ActionResult<ApiResponse<List<CustomerDetailDto>>>> GetCustomerDetailBatch(
            [FromBody] BatchGetCustomerDetailRequestDto? request)
        {
            try
            {
                if (request == null || !request.ExternalUserIds.Any())
                {
                    return BadRequest(ApiResponse<List<CustomerDetailDto>>.Error("外部联系人ID列表不能为空"));
                }

                if (request.ExternalUserIds.Count > 100)
                {
                    return BadRequest(ApiResponse<List<CustomerDetailDto>>.Error("单次最多支持查询100个客户"));
                }

                logger.LogInformation("开始批量获取客户详情: Count={Count}, CorpId={CorpId}",
                    request.ExternalUserIds.Count, request.CorpId);

                var customerDetails = new List<CustomerDetailDto>();
                var failedIds = new List<string>();

                foreach (var externalUserId in request.ExternalUserIds)
                {
                    try
                    {
                        var customerDetail = await weChatWorkService.GetCustomerDetailAsync(externalUserId, request.CorpId);
                        customerDetails.Add(customerDetail);
                    }
                    catch (Exception ex)
                    {
                        logger.LogWarning(ex, "获取单个客户详情失败: ExternalUserId={ExternalUserId}", externalUserId);
                        failedIds.Add(externalUserId);
                    }
                }

                var message = failedIds.Any() 
                    ? $"批量获取完成，成功{customerDetails.Count}个，失败{failedIds.Count}个"
                    : "批量获取客户详情成功";

                logger.LogInformation("批量获取客户详情完成: 成功={SuccessCount}, 失败={FailedCount}",
                    customerDetails.Count, failedIds.Count);

                return Ok(ApiResponse<List<CustomerDetailDto>>.Success(customerDetails, message));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "批量获取客户详情时发生异常");
                return StatusCode(500, ApiResponse<List<CustomerDetailDto>>.Error(500, "服务器内部错误，请稍后重试"));
            }
        }

        #endregion

        #region 获取企业微信JSSDK配置

        /// <summary>
        /// 获取企业微信JSSDK配置
        /// </summary>
        /// <param name="request">JSSDK配置请求</param>
        /// <returns>JSSDK配置信息</returns>
        [HttpPost("jssdk-config")]
        public async Task<ActionResult<ApiResponse<JsSdkConfigDto>>> GetJsSdkConfig(
            [FromBody] JsSdkConfigRequestDto? request)
        {
            try
            {
                if (request == null || string.IsNullOrWhiteSpace(request.Url))
                {
                    return BadRequest(ApiResponse<JsSdkConfigDto>.Error("URL参数不能为空"));
                }

                // 验证URL格式
                if (!Uri.TryCreate(request.Url, UriKind.Absolute, out var uri) || 
                    (uri.Scheme != "http" && uri.Scheme != "https"))
                {
                    return BadRequest(ApiResponse<JsSdkConfigDto>.Error("URL格式不正确，必须是有效的HTTP或HTTPS地址"));
                }

                logger.LogInformation("开始获取JSSDK配置: Url={Url}, CorpId={CorpId}, AgentId={AgentId}",
                    request.Url, request.CorpId, request.AgentId);

                var jsSdkConfig = await weChatWorkService.GetJsSdkConfigAsync(
                    request.Url, 
                    request.CorpId, 
                    request.AgentId, 
                    request.JsApiList, 
                    request.Debug ?? false);

                logger.LogInformation("成功获取JSSDK配置: Url={Url}, CorpId={CorpId}",
                    request.Url, jsSdkConfig.CorpId);

                return Ok(ApiResponse<JsSdkConfigDto>.Success(jsSdkConfig, "获取JSSDK配置成功"));
            }
            catch (UnauthorizedAccessException ex)
            {
                logger.LogWarning(ex, "获取JSSDK配置时权限不足: Url={Url}", request?.Url);
                return Unauthorized(ApiResponse<JsSdkConfigDto>.Error(401, "权限不足，请检查应用授权"));
            }
            catch (ArgumentException ex)
            {
                logger.LogWarning(ex, "获取JSSDK配置时参数错误: Url={Url}", request?.Url);
                return BadRequest(ApiResponse<JsSdkConfigDto>.Error(400, ex.Message));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取JSSDK配置时发生异常: Url={Url}", request?.Url);
                return StatusCode(500, ApiResponse<JsSdkConfigDto>.Error(500, "服务器内部错误，请稍后重试"));
            }
        }

        #endregion

        #region 获取用户身份信息

        /// <summary>
        /// 获取用户身份信息
        /// </summary>
        /// <param name="request">获取用户信息请求</param>
        /// <returns>用户身份信息</returns>
        [HttpPost("user-info")]
        public Task<ActionResult<ApiResponse<UserInfoDto>>> GetUserInfo(
            [FromBody] GetUserInfoRequestDto? request)
        {
            try
            {
                if (request == null || string.IsNullOrWhiteSpace(request.Code))
                {
                    return Task.FromResult<ActionResult<ApiResponse<UserInfoDto>>>(BadRequest(ApiResponse<UserInfoDto>.Error("授权码不能为空")));
                }

                logger.LogInformation("开始获取用户身份信息: Code={Code}, CorpId={CorpId}",
                    request.Code, request.CorpId);

                // 这里应该调用企业微信API获取用户信息
                // 由于涉及具体的API调用，这里先返回一个示例响应
                // 实际实现需要在WeChatWorkService中添加相应方法

                logger.LogWarning("获取用户身份信息功能尚未完全实现");
                return Task.FromResult<ActionResult<ApiResponse<UserInfoDto>>>(StatusCode(501, ApiResponse<UserInfoDto>.Error(501, "功能尚未实现")));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取用户身份信息时发生异常: Code={Code}", request?.Code);
                return Task.FromResult<ActionResult<ApiResponse<UserInfoDto>>>(StatusCode(500, ApiResponse<UserInfoDto>.Error(500, "服务器内部错误，请稍后重试")));
            }
        }

        #endregion
    }

    #region 批量获取客户详情请求模型

    /// <summary>
    /// 批量获取客户详情请求模型
    /// </summary>
    public class BatchGetCustomerDetailRequestDto
    {
        /// <summary>
        /// 外部联系人ID列表
        /// </summary>
        [Required(ErrorMessage = "外部联系人ID列表不能为空")]
        public List<string> ExternalUserIds { get; set; } = new List<string>();

        /// <summary>
        /// 企业ID（可选，如果不传则使用默认配置）
        /// </summary>
        public string? CorpId { get; set; }
    }

    #endregion
}